package com.zlf.sb.demo.design.zh;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/***
 *@title AwardStrategyFactory
 *@description 定义工厂方法，对外统一暴露业务调用入口：
 *@author wgc_j
 *@version 1.0.0
 *@create 2025-02-19 10:40
 **/
@Component
public class AwardStrategyFactory implements ApplicationContextAware {
    private final static Map<String, AwardStrategy> MAP = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, AwardStrategy> beanTypeMap = applicationContext.getBeansOfType(AwardStrategy.class);
        beanTypeMap.values().forEach(strategyObj -> MAP.put(strategyObj.getSource(), strategyObj));
    }
    /**
     * 对外统一暴露的工厂方法
     */
    public Boolean getAwardResult(String userId, String source) {
        AwardStrategy strategy = MAP.get(source);
        if (Objects.isNull(strategy)) {
            throw new RuntimeException("渠道异常!");
        }
        return strategy.awardStrategy(userId);
    }

    /**
     * 静态内部类创建单例工厂对象
     */
    private static class CreateFactorySingleton {
        private static AwardStrategyFactory factory = new AwardStrategyFactory();
    }

    public static AwardStrategyFactory getInstance() {
        return CreateFactorySingleton.factory;
    }
}
